package com.wuliang.generate.common.core.basic;

import com.google.gson.annotations.Expose;
import com.wuliang.generate.common.core.utils.JsonUtils;
import com.wuliang.generate.common.core.utils.PredicatesUtils;
import com.wuliang.generate.common.core.utils.VoUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.data.jpa.domain.Specification;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 邬魉
 */
@Data
public abstract class BaseVo<T extends BasicEntity> implements Serializable {

    @ApiModelProperty(name = "pageNo", value = "显示的第几页", dataType = "int")
    private Integer pageNo = 1;

    @ApiModelProperty(name = "pageSize", value = "每页显示条目数", dataType = "int")
    private Integer pageSize = 10;

    @Expose(serialize = false, deserialize = false)
    @ApiModelProperty(name = "searchKeywords", value = "要搜索的关键字对象", dataType = "object")
    private Map<String, Object> searchKeywords = new LinkedHashMap<>();

    @Expose(serialize = false, deserialize = false)
    @ApiModelProperty(name = "searchFuzzyKeyword", value = "模糊关键字查询", dataType = "string")
    private Map<String, Object> searchFuzzyKeyword = new LinkedHashMap<>();

    @Expose
    @ApiModelProperty(name = "sortedField", value = "排序的关键字", dataType = "string")
    private String sortedField;

    @Expose(deserialize = false, serialize = false)
    @ApiModelProperty(name = "idList", value = "id数组", dataType = "array")
    private List<Integer> idList = new ArrayList<>();

    /**
     * 检查要查询的关键字列表
     */
    public void checkSearchKeywords() {
        // 如果关键字列表为空，或者是关键字列表中的数据状态字段为空
        if (searchKeywords.isEmpty() || searchKeywords.get("dataStatus") == null) {
            // 则向关键字列表中追加检索未删除的数据
            searchKeywords.put("dataStatus", 0);
        }
        // 将当前对象中有值的字段转换成 map
        Map<String, Object> thisMap = JsonUtils.objectToMap(this);
        // 存放到关键字集合中
        searchKeywords.putAll(thisMap);
        // 声明当前对象名称
        String entityName = this.getClass().getSimpleName();
        // 格式化业务主键名称
        String primerKeyName =
                ((char) (entityName.charAt(0) + 32)) + entityName.substring(1, entityName.length() - 2) + "Id";
        // 调用业务主键的getter方法，以获取其值
        Object idValue = VoUtils.invokeGetIdMethod(this);
        // 如果业务主键不为空且不为零，那么追加检索条件，实体表主键为业务主键的值
        if (idValue != null && !idValue.equals(0)) {
            searchKeywords.put("ID", Integer.parseInt(idValue.toString()));
        }
        // 删除业务主键字段，
        searchKeywords.remove(primerKeyName);
    }

    /**
     * 格式化检索条件
     *
     * @return {@linkplain Specification}
     */
    public Specification<T> toSpecification() {
        // 检查检索条件
        checkSearchKeywords();
        return PredicatesUtils.getFields(searchKeywords, searchFuzzyKeyword);
    }

}
